import Toast from '@/vant'

const strategies = {
  isNonEmpty: function( value, errorMsg ) {
    if (value === '') {
      return Toast({ message: errorMsg, duration: 800 })
    }
  },
  minLength: function( value, length, errorMsg ) {
    if (value.length < length) {
      return Toast({ message: errorMsg, duration: 800 })
    }
  },
  isMobile: function( value, errorMsg ) {
    if (!/(^1[3|5|8][0-9]{9}$)/.test(value)) {
      return Toast({ message: errorMsg, duration: 800 })
    }
  }
}

class Validator {
  constructor () {
    this.cache = []
  }
  add (el, rules) {
    rules.reduce((p, c) => {
      let strategyArr = c.strategy.split(':')
      const errMsg = c.errMsg
      p.push(function () {
        const strategy = strategyArr.shift()
        strategyArr = [el, ...strategyArr, errMsg]
        return strategies[strategy].apply(el, strategyArr)
      })
      return p
    }, this.cache)
    return this
  }
  start () {
    for (let item of this.cache) {
      const result = item()
      if (result) {
        return result
      }
    }
  }
}

export default Validator

